package content

import (
	"github.com/gin-gonic/gin"
	"woo-server/coms/structs"
	"woo-server/coms/utils"
	"woo-server/models/api"
	"woo-server/models/db/content"
)

// 结构
type ArticleCategoryService struct {
	*structs.Common
}

// 初始化
func NewArticleCategoryService(com *structs.Common) *ArticleCategoryService {
	return &ArticleCategoryService{com}
}

// 文章分类列表
func (s *ArticleCategoryService) GetList(context *gin.Context) *api.ResultEntity {

	search := context.Query("search")
	page := structs.SetInt(context.Query("page"))
	pageSize := structs.SetInt(context.Query("pageSize"))
	Model := content.NewArticleCategory(s.Common)
	list, total := Model.GetListAndTotal(search, page, pageSize)
	result := map[string]interface{}{"list": list, "total": total}
	return api.SuccessToJson(result, "文章分类列表获取成功!")
}

// 当前用户信息
func (s *ArticleCategoryService) GetConfig(context *gin.Context) *api.ResultEntity {
	Model := content.NewArticleCategory(s.Common)
	data := Model.GetConfig()
	return api.SuccessToJson(data, "获取文章分类配置成功!")
}

func (s *ArticleCategoryService) PostSave(context *gin.Context) *api.ResultEntity {
	Name := context.Query("Name")
	if Name == "" {
		return api.Error("名称不能为空!")
	}
	Model := content.NewArticleCategory(s.Common)
	//fmt.Println("saveInfo",uint64(context.GetInt("AdminMenuId")))
	//params := context.QueryArray("data")
	Model.Name = Name
	Model.Sort = uint(structs.SetInt(context.Query("Sort")))
	CategoryId := uint64(structs.SetInt(context.Query("CategoryId")))
	var err error
	if CategoryId == 0 {

		// 基础参数
		Model.SetCreateInfo(s.Claim.UserId)
		// 执行创建
		err = Model.Create()
	} else {
		Model.CategoryId = CategoryId
		err = Model.Save()

	}
	if err != nil {
		// 日志
		utils.LogError("新增文章分类报错:%s", err.Error())
		return api.Error(err.Error())
	}
	return api.Success("success")
}

func (s *ArticleCategoryService) Delete(context *gin.Context) *api.ResultEntity {
	//context.Param()
	// 接收POST参数
	CategoryId := context.PostForm("CategoryId")
	// 校验参数
	if CategoryId == "" {
		return api.Error("ID不能为空!")
	}
	// 实例化数据库
	Model := content.NewArticleCategory(s.Common)
	// 执行删除
	Model.CategoryId = uint64(structs.SetInt(CategoryId))
	// 删除数据
	err := Model.Delete()
	if err != nil {
		utils.LogError("删除文章分类报错:%s", err.Error())
		return api.Error(err.Error())
	}
	return api.Success("删除成功")
}
